package practice.lucene.part01;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.springframework.ui.context.HierarchicalThemeSource;
import practice.common.Constant;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Date;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-4-21
 * Time: 下午7:23
 * lucene实践之hellolucene
 */
public class HelloLucene {


    //创建索引对象
    public void createIndex(File indexFile) throws Exception {
        //1,创建一个Directory目录
        //创建一个基于内存的索引
//        Directory directory = new RAMDirectory();
        Directory directory = FSDirectory.open(indexFile);
        //2.创建IndexWriter
        IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
        IndexWriter writer = new IndexWriter(directory, conf);
        //3,创建document对象
        File dataDir = new File("D:/01_FSM/05_3阶段工作文档");
        //遍历文件夹，给每个文件做一个索引
        File[] dataFiles = dataDir.listFiles();
        long startTime = new Date().getTime();
        for (int i = 0; i < dataFiles.length; i++) {
            File file = dataFiles[i];
            if (file.isFile() && file.getName().endsWith(".txt")) {
                Document doc = new Document();
                //4,为document添加Field
                System.out.println("正在给文件创建索引：" + file.getName());
                doc.add(new Field("content", new FileReader(file)));
                doc.add(new Field("filename", file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("path", file.getAbsolutePath(), Field.Store.YES, Field.Index.ANALYZED));
                writer.addDocument(doc);
            }

        }
        long endTime = new Date().getTime();
        System.out.println("It takes " + (endTime - startTime)
                + " milliseconds to create index for the files in directory "
                + dataDir.getPath());
        //5,通过indexReader添加文档到索引中。
        writer.close();
        directory.close();

    }

    public void searcherIndex(File indexFile) throws Exception {
        FSDirectory directory = FSDirectory.open(indexFile);
        String queryString = "刘强";
        IndexSearcher searcher = new IndexSearcher(directory);
        if (!indexFile.exists()) {
            System.out.println("The Lucene index is not exist");
            return;
        }
        Term term = new Term("content", queryString.toLowerCase());
        TermQuery lucence = new TermQuery(term);
        TopDocs docs = searcher.search(lucence, 10);
        for (int i = 0; i < docs.totalHits; i++) {
            ScoreDoc socre = docs.scoreDocs[i];
            Document doc = new Document();
        }

    }

    public void searcher2Index(File indexFile) throws Exception {
        System.out.println("search begin");
        FSDirectory directory = FSDirectory.open(indexFile);
        IndexReader reader = IndexReader.open(directory);
        IndexSearcher searcher = new IndexSearcher(reader);
        //创建搜索用的解析器
        //创建parser来确定要搜索文件的内容，第二个参数指定搜索的域
        QueryParser parser = new QueryParser(Version.LUCENE_36, "content", new StandardAnalyzer(Version.LUCENE_36));
        String queryString = "wap";
        //创建query，搜索context包含 queryString的文档
        Query query = parser.parse(queryString);
        TopDocs tds = searcher.search(query, 10);   //指定搜索的条目
        ScoreDoc[] socreDoc = tds.scoreDocs;
        for (ScoreDoc sd : socreDoc) {
            //根据searcher和ScoreDoc对象获取具体的document对象
            Document doc = searcher.doc(sd.doc);
            System.out.println(doc.get("filename") + "[" + doc.get("path") + "]");
        }
        reader.close();
        System.out.println("search end");

    }

    public static void main(String[] args) {
        try {
            File indexDir = new File(Constant.lucencePath);
            HelloLucene demo = new HelloLucene();
            demo.createIndex(indexDir);
            demo.searcher2Index(indexDir);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
